package cn.schoolwow.quickdao.module.database.dql.response.flow;

import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dql.parent.domain.QueryContext;
import cn.schoolwow.quickdao.module.database.dql.subCondition.domain.SubQueryOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class GetListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QueryContext queryContext = (QueryContext) flowContext.checkData("queryContext");
        JSONArray resultSetArray = (JSONArray) flowContext.getData("resultSetArray");
        if(null==resultSetArray||resultSetArray.isEmpty()){
            flowContext.putData("array", new JSONArray());
            return;
        }

        JSONArray array = new JSONArray(resultSetArray.size());
        for(int i=0;i<resultSetArray.size();i++){
            JSONObject resultSetObject = resultSetArray.getJSONObject(i);

            JSONObject instance = new JSONObject();
            //主表字段
            for(Property property:queryContext.queryOption.queryTableOption.entity.properties){
                String columnLabel = queryContext.queryOption.queryTableOption.tableAliasName+"_"+property.column;
                if(resultSetObject.containsKey(columnLabel)){
                    instance.put(property.name, resultSetObject.get(columnLabel));
                    resultSetObject.remove(columnLabel);
                }
            }
            //关联表字段
            for (SubQueryOption subQueryOption : queryContext.queryOption.subQueryOptionList) {
                if (null == subQueryOption.subQueryJoinTableOption.compositeFieldName || subQueryOption.subQueryJoinTableOption.compositeFieldName.isEmpty()) {
                    continue;
                }
                JSONObject compositeInstance = new JSONObject();
                for(Property property:subQueryOption.subQueryTableOption.entity.properties){
                    String columnLabel = subQueryOption.subQueryTableOption.tableAliasName+"_"+property.column;
                    if(resultSetObject.containsKey(columnLabel)){
                        compositeInstance.put(property.name, resultSetObject.get(columnLabel));
                        resultSetObject.remove(columnLabel);
                    }
                }
                instance.put(subQueryOption.subQueryJoinTableOption.compositeFieldName, compositeInstance);
            }
            instance.putAll(resultSetObject);
            array.add(instance);
        }
        flowContext.putData("array", array);
    }

    @Override
    public String name() {
        return "获取实体类返回列表";
    }

}
